﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data;
using System.Web.UI.HtmlControls;
using Aspose.Excel;

namespace LenderClearingHouse
{
  public partial class GlobalGrid : PageBase
  {
      protected void Page_Load(object sender, EventArgs e)
      {
          Session["SourcePage"] = SourcePage.GlobalGrid;
          listFilter.SearchButton.Click += new ImageClickEventHandler(SearchButton_Click);
          gridLvreo.HeaderContextMenu.PreRender += new EventHandler(HeaderContextMenu_PreRender);
          gridLvreo.SortCommand += new GridSortCommandEventHandler(grid_SortCommand);

          radAjaxManager.AjaxSettings.AddAjaxSetting(gridLvreo, gridLvreo);

          if (!IsPostBack)
          {
              FillNameSettings();

              /*List<string> lstMain = MainGridColumnsList(gridLvreo);
              HideSubGridColumns(lstMain, gridFinancial);
              HideSubGridColumns(lstMain, gridEscrow);

              gridLvreo.ClientSettings.AllowColumnsReorder = true;
              gridFinancial.ClientSettings.AllowColumnsReorder = true;
              gridEscrow.ClientSettings.AllowColumnsReorder = true;*/

              GetColumnsMatrix();
              SaveSortedPropertyIdsToSession(null);
          }

      }

    void SearchButton_Click(object sender, ImageClickEventArgs e)
    {
        gridLvreo.Rebind();
    }

    void HeaderContextMenu_PreRender(object sender, EventArgs e)
    {
      RemoveHeaderContextMenuColumnsByUniqueName("Address", (sender as GridHeaderContextMenu).GetAllItems());
    }

    void RemoveHeaderContextMenuColumnsByUniqueName(string uniqueName, IList<RadMenuItem> menuItems)
    {
      for (int topItemIndex = 0; topItemIndex <= menuItems.Count - 1; topItemIndex++)
      {
        if (menuItems[topItemIndex].Text == "Columns")
        {
          var lowerMenuItemsCount = menuItems[topItemIndex].Items.Count;
          for (int lowerItemIndex = lowerMenuItemsCount - 1; lowerItemIndex >= 0; lowerItemIndex--)
          {
            string strName = menuItems[topItemIndex].Items[lowerItemIndex].Value;
            string strColName = strName.Split('|')[1];
            if (uniqueName == strColName)
            {
              menuItems[topItemIndex].Items.RemoveAt(lowerItemIndex);
            }
          }
        }
      }
    }

    RadGrid gridLvreo = new RadGrid();
    
    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);
      
      gridLvreo.ID = "gridLvreo";      
      
      CreateLvreoColumns(SetupGrid(gridLvreo, dsLvreo));
      phLvreoGrid.Controls.Add(gridLvreo);
    }

    void grid_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e)
    {
        Session[GridPageSizeSessionKey] = e.NewPageSize.ToString();
    }

    RadGrid SetupGrid(RadGrid grid, SqlDataSource dataSource)
    {
      grid.ShowStatusBar = true;
      grid.AutoGenerateColumns = false;
      grid.AllowSorting = true;
      grid.AllowPaging = true;
      grid.AllowFilteringByColumn = true;
      grid.GroupingEnabled = false;
      grid.GroupingSettings.CaseSensitive = false;
      grid.MasterTableView.Width = Unit.Percentage(100);
      grid.MasterTableView.DataKeyNames = new string[] { "PropertyId" };
      grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
      grid.MasterTableView.EnableHeaderContextMenu = true;
      grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
      grid.Width = Unit.Pixel(1160);
      grid.ClientSettings.Scrolling.AllowScroll = true;
      grid.ClientSettings.Scrolling.UseStaticHeaders = true;
      grid.ClientSettings.Scrolling.SaveScrollPosition = true;
      grid.ClientSettings.Scrolling.ScrollHeight = Unit.Pixel(500);
      grid.ClientSettings.Scrolling.FrozenColumnsCount = 1;
      grid.ClientSettings.AllowColumnsReorder = true;
      grid.ClientSettings.ReorderColumnsOnClient = true;

      grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
      grid.PagerStyle.AlwaysVisible = true;
      grid.DataSourceID = dataSource.ID;

      grid.PageSizeChanged += new GridPageSizeChangedEventHandler(grid_PageSizeChanged);      

      try
      {
          grid.PageSize = int.Parse(Session[GridPageSizeSessionKey].ToString());
      }
      catch
      {
          grid.PageSize = 20;
      }

      grid.ItemDataBound += new GridItemEventHandler(grid_ItemDataBound);

      return grid;
    }

    protected void dsLvreo_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        e.Command.Parameters["@Apn"].Value = listFilter.Apn;
        e.Command.Parameters["@PropLocation"].Value = listFilter.Address;
        e.Command.Parameters["@Zip"].Value = listFilter.Zip;
    }

    GridTemplateColumn AddDollarColumn(GridColumnCollection columns, string fieldName, string headerText, bool readOnly, int editFormColumnIndex)
    {
      GridTemplateColumn gtc = new GridTemplateColumn()
      {
        UniqueName = fieldName,
        HeaderText = headerText,
        ItemTemplate = new DollarColumn(fieldName),
        EditItemTemplate = new CurrencyColumnEdit(fieldName),
        ConvertEmptyStringToNull = false,
        EditFormColumnIndex = editFormColumnIndex,
        DataField = fieldName,
        SortExpression = fieldName,
        ReadOnly = readOnly
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);

      return gtc;
    }

    void CreateLvreoColumns(RadGrid grid)
    {
      GridBoundColumn col;
      GridTemplateColumn gtc;
      GridHyperLinkColumn hlc;

      // 1-st grid
      /*col = new GridBoundColumn();
      col.DataField = "PropertyLocation";
      col.HeaderText = "Address";
      col.UniqueName = "Address";
      col.ConvertEmptyStringToNull = false;
      col.ReadOnly = true;
      col.Display = true;
      col.HeaderStyle.Width = Unit.Pixel(150);
      col.Reorderable = false;
      grid.Columns.Add(col);*/
        
      hlc = new GridHyperLinkColumn()
      {
          HeaderText = "Address",
          DataNavigateUrlFormatString = "~/PropertyDetails2.aspx?propertyId={0}",
          DataNavigateUrlFields = new string[] { "PropertyId" },
          EditFormColumnIndex = 0,
          DataTextField = "PropertyLocation",
          SortExpression = "PropertyLocation",
          UniqueName = "Address",
      };
      hlc.Display = true;
      hlc.HeaderStyle.Width = Unit.Pixel(150);
      hlc.Reorderable = false;
      grid.Columns.Add(hlc);

      gtc = new GridTemplateColumn()
      {
        UniqueName = "InvestorName",
        HeaderText = "Investor",
        ItemTemplate = new SpanColumn("InvestorName"),
        ConvertEmptyStringToNull = false,
        EditFormColumnIndex = 0,
        DataField = "InvestorName",
        SortExpression = "InvestorName"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      gtc = new GridTemplateColumn()
      {
        UniqueName = "ListingStatus",
        HeaderText = "Status",
        ItemTemplate = new SpanColumn("ListingStatus"),
        EditItemTemplate = new StatusColumnEdit("ListingStatus"),
        EditFormColumnIndex = 0,
        SortExpression = "ListingStatus",
        DataField = "ListingStatus"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      col = new GridBoundColumn();
      col.DataField = "CloseDate";
      col.HeaderText = "Close Date";
      col.ConvertEmptyStringToNull = false;
      col.DataType = typeof(DateTime);
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 42
      col = new GridBoundColumn();
      col.DataField = "Source";
      col.HeaderText = "Source";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 31
      col = new GridBoundColumn();
      col.DataField = "DateRecorded";
      col.HeaderText = "Date of Reservation";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.DataType = typeof(DateTime);
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 37
      col = new GridBoundColumn();
      col.DataField = "EscrowCompany";
      col.HeaderText = "Company";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 2;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      gtc = new GridTemplateColumn()
      {
        UniqueName = "Apn",
        HeaderText = "Apn",
        ItemTemplate = new SpanColumn("Apn"),
        EditItemTemplate = new RequiredColumnEdit("Apn"),
        EditFormColumnIndex = 0,
        SortExpression = "Apn",
        DataField = "Apn"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      /*// 5
      hlc = new GridHyperLinkColumn()
      {
        HeaderText = "PropertyLocation",
        DataNavigateUrlFormatString = "~/PropertyDetails.aspx?propertyId={0}",
        DataNavigateUrlFields = new string[] { "PropertyId" },
        EditFormColumnIndex = 0,
        DataTextField = "PropertyLocation",
        SortExpression = "PropertyLocation"
      };
      hlc.HeaderStyle.Width = Unit.Pixel(150);
      grid.Columns.Add(hlc);*/

      // 6
      col = new GridBoundColumn();
      col.DataField = "ZipCode";
      col.HeaderText = "ZipCode";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 0;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 33
      col = new GridBoundColumn();
      col.DataField = "AssessorDesc";
      col.HeaderText = "AssessorDesc";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH * 3);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH * 3 - 40);
      grid.Columns.Add(col);

      // 8
      gtc = new GridTemplateColumn()
      {
        UniqueName = "HOA",
        HeaderText = "HOA",
        ItemTemplate = new DollarColumn("HOA"),
        EditItemTemplate = new CurrencyColumnEdit("HOA"),
        ConvertEmptyStringToNull = false,
        EditFormColumnIndex = 0,
        DataField = "HOA",
        SortExpression = "HOA"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      // 9
      col = new GridBoundColumn();
      col.DataField = "Stories";
      col.HeaderText = "Stories";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 0;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 10
      col = new GridBoundColumn();
      col.DataField = "ConstructYear";
      col.HeaderText = "ConstYear";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 11
      col = new GridBoundColumn();
      col.DataField = "TotalSqft";
      col.HeaderText = "TotalSqft";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 12
      col = new GridBoundColumn();
      col.DataField = "LotSize";
      col.HeaderText = "LotSize";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 13
      gtc = new GridTemplateColumn()
      {
        UniqueName = "Bedrooms",
        HeaderText = "Bed",
        ItemTemplate = new SpanColumn("Bedrooms"),
        EditItemTemplate = new RoomsColumnEdit("Bedrooms"),
        EditFormColumnIndex = 1,
        DataField = "Bedrooms",
        SortExpression = "Bedrooms"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      // 14
      col = new GridBoundColumn();
      col.DataField = "Bathrooms";
      col.HeaderText = "Bath";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 15
      col = new GridBoundColumn();
      col.DataField = "GarageSqft";
      col.HeaderText = "GarageSqft";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 1;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      // 16
      gtc = new GridTemplateColumn()
      {
        UniqueName = "Pool",
        HeaderText = "Pool",
        ItemTemplate = new SpanColumn("Pool"),
        EditItemTemplate = new YesNoColumnEdit("Pool"),
        EditFormColumnIndex = 1,
        DataField = "Pool",
        SortExpression = "Pool"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      // 17
      gtc = new GridTemplateColumn()
      {
        UniqueName = "Spa",
        HeaderText = "Spa",
        ItemTemplate = new SpanColumn("Spa"),
        EditItemTemplate = new YesNoColumnEdit("Spa"),
        EditFormColumnIndex = 2,
        DataField = "Spa",
        SortExpression = "Spa"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      // 39
      col = new GridBoundColumn();
      col.DataField = "PrelistStatus";
      col.HeaderText = "Prelist Status";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 2;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      gtc = new GridTemplateColumn()
      {
        UniqueName = "PurchasePrice",
        HeaderText = "Purchase Price",
        ItemTemplate = new DollarColumn("PurchasePrice"),
        EditItemTemplate = new CurrencyColumnEdit("PurchasePrice"),
        ConvertEmptyStringToNull = false,
        EditFormColumnIndex = 2,
        DataField = "PurchasePrice",
        SortExpression = "PurchasePrice"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      // 41
      gtc = new GridTemplateColumn()
      {
        UniqueName = "RehabCosts",
        HeaderText = "Rehab Costs",
        ItemTemplate = new DollarColumn("RehabCosts"),
        EditItemTemplate = new CurrencyColumnEdit("RehabCosts"),
        ConvertEmptyStringToNull = false,
        EditFormColumnIndex = 3,
        DataField = "RehabCosts",
        SortExpression = "RehabCosts"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      // 38
      col = new GridBoundColumn();
      col.DataField = "MiscNotes";
      col.HeaderText = "Misc Notes";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 2;
      col.HeaderStyle.Width = Unit.Pixel(400);
      col.FilterControlWidth = Unit.Pixel(360);
      grid.Columns.Add(col);

      // 32
      col = new GridBoundColumn();
      col.DataField = "LandUse";
      col.HeaderText = "LandUse";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH * 2);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH * 2 - 40);
      grid.Columns.Add(col);

      // 34
      gtc = new GridTemplateColumn()
      {
        UniqueName = "Phase",
        HeaderText = "Phase",
        ItemTemplate = new SpanColumn("Phase"),
        EditItemTemplate = new PhaseColumnEdit("Phase"),
        ConvertEmptyStringToNull = false,
        EditFormColumnIndex = 3,
        DataField = "Phase",
        SortExpression = "Phase"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      // 2-d grid
      col = new GridBoundColumn();
      col.DataField = "EMD";
      col.HeaderText = "EMD";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "Reimb";
      col.HeaderText = "Reimb";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "Insur";
      col.HeaderText = "Insur";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "DateAccept";
      col.HeaderText = "Date Accept";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.DataType = typeof(DateTime);
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "StartDate";
      col.HeaderText = "Start Date";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.DataType = typeof(DateTime);
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      gtc = AddDollarColumn(grid.Columns, "ClosingCost", "Closing Cost", true, 3);
      grid.Columns.Add(gtc);
      
      gtc = new GridTemplateColumn()
      {
        UniqueName = "Assmts",
        HeaderText = "Assmts",
        ItemTemplate = new SpanColumn("Assmts"),
        EditItemTemplate = new YesNoColumnEdit("Assmts"),
        EditFormColumnIndex = 1,
        DataField = "Assmts",
        SortExpression = "Assmts"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(gtc);

      gtc = AddDollarColumn(grid.Columns, "PurchaseNoteTotal", "Purchase/Note Total", true, 3);
      grid.Columns.Add(gtc);

      gtc = AddDollarColumn(grid.Columns, "PurchaseCostSqft", "Purchase Cost/Sqft", true, 3);
      grid.Columns.Add(gtc);

      gtc = AddDollarColumn(grid.Columns, "EstimatedSale", "Estimated Sale", false, 3);
      grid.Columns.Add(gtc);

      gtc = AddDollarColumn(grid.Columns, "SaleCostSqft", "Sale Cost/Sqft", true, 3);
      grid.Columns.Add(gtc);

      gtc = AddDollarColumn(grid.Columns, "CostOfSale", "Cost Of Sale", true, 3);
      grid.Columns.Add(gtc);

      gtc = AddDollarColumn(grid.Columns, "NetDemandToEscrow", "Net Demand To Escrow", true, 3);
      grid.Columns.Add(gtc);

      gtc = AddDollarColumn(grid.Columns, "NetProfit", "Net Profit", true, 3);
      grid.Columns.Add(gtc);

      col = new GridBoundColumn();
      col.DataField = "PercentOfProfitVsPurchase";
      col.HeaderText = "% Of Profit vs Purchase";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      col.ReadOnly = true;
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "CostToARV";
      col.HeaderText = "Cost To ARV";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      col.ReadOnly = true;
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "TotalDays";
      col.HeaderText = "Total Days";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      col.ReadOnly = true;
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "FeePercent";
      col.HeaderText = "Fee Percent";
      col.ConvertEmptyStringToNull = false;
      col.EditFormColumnIndex = 3;
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);


      // 3-d
      col = new GridBoundColumn();
      col.DataField = "PurchaseAgreementReceived";
      col.HeaderText = "Purchase Agreement Received";
      col.DataType = typeof(DateTime);
      col.SortExpression="PurchaseAgreementReceived";
      col.UniqueName = "PurchaseAgreementReceived";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "CAP";
      col.HeaderText = "CAP";
      col.SortExpression = "CAP";
      col.UniqueName = "CAP";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "TitleCompanyFront";
      col.HeaderText = "Title Company Front";
      col.SortExpression = "TitleCompanyFront";
      col.UniqueName = "TitleCompanyFront";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "Loan";
      col.HeaderText = "Loan";
      col.SortExpression = "Loan";
      col.UniqueName = "Loan";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "LoanInfo";
      col.HeaderText = "LoanInfo";
      col.SortExpression = "LoanInfo";
      col.UniqueName = "LoanInfo";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "EffectiveDateBank";
      col.HeaderText = "Effective Date Bank";
      col.DataType = typeof(DateTime);
      col.SortExpression = "EffectiveDateBank";
      col.UniqueName = "EffectiveDateBank";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "ECOE_F";
      col.HeaderText = "ECOE - F";
      col.DataType = typeof(DateTime);
      col.SortExpression = "ECOE_F";
      col.UniqueName = "ECOE_F";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      gtc = AddDollarColumn(grid.Columns, "AdjPurchasePrice", "Adj Purchase Price", false, 3);
      grid.Columns.Add(gtc);

      col = new GridBoundColumn();
      col.DataField = "RECORDED_F";
      col.HeaderText = "RECORDED - F";
      col.DataType = typeof(DateTime);
      col.SortExpression = "RECORDED_F";
      col.UniqueName = "RECORDED_F";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "CommentsFront";
      col.HeaderText = "Comments Front";
      col.SortExpression = "CommentsFront";
      col.UniqueName = "CommentsFront";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "ListingAgreement";
      col.HeaderText = "Listing Agreement";
      col.DataType = typeof(DateTime);
      col.SortExpression = "ListingAgreement";
      col.UniqueName = "ListingAgreement";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "ContractDate";
      col.HeaderText = "Contract Date";
      col.DataType = typeof(DateTime);
      col.SortExpression = "ContractDate";
      col.UniqueName = "ContractDate";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "ECOE_B";
      col.HeaderText = "ECOE - B";
      col.DataType = typeof(DateTime);
      col.SortExpression = "ECOE_B";
      col.UniqueName = "ECOE_B";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "Recorded_B";
      col.HeaderText = "Recorded - B";
      col.DataType = typeof(DateTime);
      col.SortExpression = "Recorded_B";
      col.UniqueName = "Recorded_B";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      gtc = AddDollarColumn(grid.Columns, "BuyerPurchasePrice", "Buyer Purchase Price", false, 3);
      grid.Columns.Add(gtc);

      col = new GridBoundColumn();
      col.DataField = "PurchaseType";
      col.HeaderText = "Purchase Type";
      col.SortExpression = "PurchaseType";
      col.UniqueName = "PurchaseType";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "Incentive";
      col.HeaderText = "Incentive";
      col.SortExpression = "Incentive";
      col.UniqueName = "Incentive";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "HOAManagement";
      col.HeaderText = "HOA & Management";
      col.SortExpression = "HOAManagement";
      col.UniqueName = "HOAManagement";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      gtc = AddDollarColumn(grid.Columns, "MonthlyHOADues", "Monthly HOA Dues", false, 3);
      grid.Columns.Add(gtc);

      col = new GridBoundColumn();
      col.DataField = "PastDueHOA";
      col.HeaderText = "Past due HOA";
      col.SortExpression = "PastDueHOA";
      col.UniqueName = "PastDueHOA";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "ResalePacketOrdered";
      col.HeaderText = "Resale Packet Ordered";
      col.DataType = typeof(DateTime);
      col.SortExpression = "ResalePacketOrdered";
      col.UniqueName = "ResalePacketOrdered";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "ResalePkgToAgent";
      col.HeaderText = "Resale Pkg to Agent";
      col.SortExpression = "ResalePkgToAgent";
      col.UniqueName = "ResalePkgToAgent";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "TitleCompanyBack";
      col.HeaderText = "Title Company Back";
      col.SortExpression = "TitleCompanyBack";
      col.UniqueName = "TitleCompanyBack";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "BuyerName";
      col.HeaderText = "Buyer's Name";
      col.SortExpression = "BuyerName";
      col.UniqueName = "BuyerName";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "COOPAgent";
      col.HeaderText = "COOP Agent";
      col.SortExpression = "COOPAgent";
      col.UniqueName = "COOPAgent";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "Lender";
      col.HeaderText = "Lender";
      col.SortExpression = "Lender";
      col.UniqueName = "Lender";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "WalkThrough";
      col.HeaderText = "Walk Through";
      col.DataType = typeof(DateTime);
      col.SortExpression = "WalkThrough";
      col.UniqueName = "WalkThrough";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "DocsIn";
      col.HeaderText = "Doc's In";
      col.DataType = typeof(DateTime);
      col.SortExpression = "DocsIn";
      col.UniqueName = "DocsIn";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "SellerSign";
      col.HeaderText = "Seller Sign";
      col.DataType = typeof(DateTime);
      col.SortExpression = "SellerSign";
      col.UniqueName = "SellerSign";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "BuyerSign";
      col.HeaderText = "Buyer Sign";
      col.DataType = typeof(DateTime);
      col.SortExpression = "BuyerSign";
      col.UniqueName = "BuyerSign";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "CommentsBack";
      col.HeaderText = "Comments Back";
      col.SortExpression = "CommentsBack";
      col.UniqueName = "CommentsBack";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

        //--- Rehab columns ---
      col = new GridBoundColumn();
      col.DataField = "RehabStatus";
      col.HeaderText = "Rehab Status";
      col.SortExpression = "RehabStatus";
      col.UniqueName = "RehabStatus";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "ProjectManager";
      col.HeaderText = "Project Mgr";
      col.SortExpression = "ProjectManager";
      col.UniqueName = "ProjectManager";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "RehabStartDate";
      col.HeaderText = "Rehab Start Date";
      col.SortExpression = "RehabStartDate";
      col.UniqueName = "RehabStartDate";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "EstRehabCompDate";
      col.HeaderText = "Est Rehab Comp Date";
      col.SortExpression = "EstRehabCompDate";
      col.UniqueName = "EstRehabCompDate";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "ActualCompDate";
      col.HeaderText = "Actual Comp Date";
      col.SortExpression = "ActualCompDate";
      col.UniqueName = "ActualCompDate";
      col.DataFormatString = "{0:MM/dd/yyyy}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "CurrentRehabCosts";
      col.HeaderText = "Current Rehab Costs";
      col.SortExpression = "CurrentRehabCosts";
      col.UniqueName = "CurrentRehabCosts";
      col.DataFormatString = "{0:c}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "NotesStatus";
      col.HeaderText = "Notes - Status";
      col.SortExpression = "NotesStatus";
      col.UniqueName = "NotesStatus";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "RehabEstimate";
      col.HeaderText = "Rehab Estimate";
      col.SortExpression = "RehabEstimate";
      col.UniqueName = "RehabEstimate";
      col.DataFormatString = "{0:c}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);

      col = new GridBoundColumn();
      col.DataField = "RehabMiscCosts";
      col.HeaderText = "Misc Costs";
      col.SortExpression = "RehabMiscCosts";
      col.UniqueName = "RehabMiscCosts";
      col.DataFormatString = "{0:c}";
      col.HeaderStyle.Width = Unit.Pixel(GridPage.INT_COMMON_WIDTH);
      col.FilterControlWidth = Unit.Pixel(GridPage.INT_COMMON_WIDTH - 40);
      grid.Columns.Add(col);
    }

    string GridPageSizeSessionKey { get { return "GridPageSize_" + this.GetType().Name; } }

    void grid_ItemDataBound(object sender, GridItemEventArgs e)
    {
      if (e.Item is GridPagerItem)
      {
        GridPagerItem item = e.Item as GridPagerItem;
        RadComboBox combo = (RadComboBox)item.FindControl("PageSizeComboBox");

        RadComboBoxItem newItem = combo.Items.FindItemByValue("100");
        if (newItem == null)
        {
          RadComboBoxItem citem = new RadComboBoxItem("100", "100");
          citem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
          combo.Items.Add(citem);
        }
        else
        {
          newItem.Text = "100";
        }

        newItem = combo.Items.FindItemByValue("1000000");
        if (newItem == null)
        {
          RadComboBoxItem citem = new RadComboBoxItem("ALL", "1000000");
          citem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
          combo.Items.Add(citem);

          if (gridLvreo.PageSize == 1000000)
          {
              combo.SelectedValue = "1000000";
          }
        }
        else
        {
          newItem.Text = "ALL";
        }
      }
      else if (e.Item is GridDataItem)
      {
        GridDataItem itm = e.Item as GridDataItem;
        DataRowView drw = itm.DataItem as DataRowView;
        if (drw["CloseDate"] != DBNull.Value)
        {
          itm.BackColor = System.Drawing.Color.FromArgb(204, 153, 255);
        }

        string notesStatus = "";
        if (drw["NotesStatus"] != DBNull.Value)
          notesStatus += drw["NotesStatus"].ToString();
        if (drw["NotesStatusDate"] != DBNull.Value)
          notesStatus += " (" + Convert.ToDateTime(drw["NotesStatusDate"]).ToString("MM/dd/yyyy hh:mm tt") + " " + drw["NotesStatusUser"].ToString() + ")";
        itm["NotesStatus"].Text = notesStatus;
      }
    }

    protected void lnkExportToExcel_Click(object sender, EventArgs e)
    {
        DataView dv = new DataView();
        DataTable dt = new DataTable();
        dv = (DataView)(gridLvreo.DataSourceObject as SqlDataSource).Select(DataSourceSelectArguments.Empty);
        dt = dv.ToTable();

        Excel ex = Utilities.GetExcel();
        Worksheet ws = ex.Worksheets[0];

        int startRow = 0;
        Utilities.GridToExcel(dt, gridLvreo, ws, true, ref startRow);
        ex.Save("GlobalGrid.xls", FileFormatType.Excel2003, SaveType.OpenInExcel, HttpContext.Current.Response);
        HttpContext.Current.Response.End();

    }

    protected void GetColumnsMatrix()
    {
      /*RadGrid grid;

      DataTable dt = new DataTable("DataColumns");
      dt.Columns.Add("NameColumn", typeof(string));
      dt.Columns.Add("Flag1", typeof(bool));
      dt.Columns.Add("Flag2", typeof(bool));
      dt.Columns.Add("Flag3", typeof(bool));

      for (int j = 1; j <= 3; ++j)
      {
        if (j == 1)
          grid = gridLvreo;
        else if (j == 2)
          grid = gridFinancial;
        else if (j == 3)
          grid = gridEscrow;
        else
          continue;

        for (int i = 0; i < grid.Columns.Count; ++i)
        {
          string dataField = "";

          if (grid.Columns[i] is GridBoundColumn)
            dataField = (grid.Columns[i] as GridBoundColumn).DataField;
          else if (grid.Columns[i] is GridTemplateColumn)
            dataField = (grid.Columns[i] as GridTemplateColumn).DataField;
          else if (grid.Columns[i] is GridHyperLinkColumn)
            dataField = (grid.Columns[i] as GridHyperLinkColumn).DataTextField;

          if (dataField == "")
            continue;

          DataRow[] drs = dt.Select(string.Format("NameColumn='{0}'", dataField));
          if (drs.Length > 0)
            drs[0][string.Format("Flag{0}", j.ToString())] = true;
          else
            dt.LoadDataRow(new object[] { dataField, j == 1, j == 2, j == 3 }, true);
        }
      }

      dt.WriteXml("C:\\DataColumns.xml", XmlWriteMode.WriteSchema);*/

    }
    
    #region GridSettings
    protected int CurrentViewUserId
    {
      get
      {
        if (Session["CurrentViewUserId"] == null)
          return -1;

        return Convert.ToInt32(Session["CurrentViewUserId"]);
      }
      set
      {
        Session["CurrentViewUserId"] = value;
      }
    }

    protected bool CurrentViewFlagGlobal
    {
      get
      {
        if (Session["CurrentViewUserId"] == null)
          return false;

        return Convert.ToBoolean(Session["CurrentViewFlagGlobal"]);
      }
      set
      {
        Session["CurrentViewFlagGlobal"] = value;
      }
    }

    protected void FillNameSettings()
    {
      ddlNameSettings.Items.Clear();
      ddlNameSettings.Items.Add(new ListItem("(Empty)", "(Empty)"));
      ddlNameSettings.SelectedIndex = 0;

      DataAccess da = new DataAccess();
      DataTable dt = da.GetDataTable("getGridSettings", new string[] { "@currentUserId" }, new object[] { this.CurrentUser.UserId });
      foreach (DataRow dr in dt.Rows)
      {
        ddlNameSettings.Items.Add(new ListItem(dr["CaptionSettings"].ToString(), dr["NameSettings"].ToString()));
      }

      chkLvreo.Checked = true;
      chkFinancial.Checked = true;
      chkEscrow.Checked = true;
      chkRehab.Checked = true;

      CurrentViewUserId = Convert.ToInt32(CurrentUser.UserId);
      CurrentViewFlagGlobal = false;
      Session["NameSettingsCurrent"] = ddlNameSettings.SelectedValue;

      ManageEnabledButtonsView();
    }

    protected void ManageEnabledButtonsView()
    {
      btnSaveView.Enabled = false;
      btnSaveViewAs.Enabled = false;
      btnDeleteView.Enabled = false;
      
      if (ddlNameSettings.SelectedIndex == 0)
      {
        btnSaveViewAs.Enabled = true;
      }
      else if (CurrentViewUserId == Convert.ToInt32(this.CurrentUser.UserId))
      {
        btnSaveView.Enabled = true;
        btnSaveViewAs.Enabled = true;
        btnDeleteView.Enabled = true;
      }
      else
      {
        btnSaveViewAs.Enabled = true;
      }
    }

    protected void SaveSettingsAs(string newName, bool flagGlobal)
    {
      DataAccess da = new DataAccess();
      string nameGrid;
      string settingsGrid;
      
      nameGrid = "gridLvreo";
      settingsGrid = new GridSettingsPersister(gridLvreo).SaveSettings();

      da.ExecuteProcedure("insertGridSettings",
        new string[] { "@OldNameSettings", "@NameSettings", "@NameGrid", "@UserId", "@FlagGlobal", "@Flag1Visible",
            "@Flag2Visible", "@Flag3Visible", "@Settings", "@FlagRehabVisible" },
        new object[] { ddlNameSettings.SelectedValue, newName, nameGrid, this.CurrentUser.UserId, flagGlobal,
            chkLvreo.Checked, chkFinancial.Checked, chkEscrow.Checked, settingsGrid, chkRehab.Checked });

      if (Session["NameSettingsNew"] != null)
      {
        FillNameSettings();
        Session["NameSettingsCurrent"] = Session["NameSettingsNew"].ToString();
        Session["NameSettingsNew"] = null;

        ddlNameSettings.SelectedValue = Session["NameSettingsCurrent"].ToString();
        LoadView();
      }
     
    }

    protected void SetColumnsByCheck(CheckBox check)
    {
      DataTable dtColumns = new DataTable();
      dtColumns.ReadXml(Server.MapPath("~/DataColumns.xml"));

      for (int i = 1; i < gridLvreo.Columns.Count; ++i)
      {
        string dataField = "";

        if (gridLvreo.Columns[i] is GridBoundColumn)
          dataField = (gridLvreo.Columns[i] as GridBoundColumn).DataField;
        else if (gridLvreo.Columns[i] is GridTemplateColumn)
          dataField = (gridLvreo.Columns[i] as GridTemplateColumn).DataField;
        else if (gridLvreo.Columns[i] is GridHyperLinkColumn)
          dataField = (gridLvreo.Columns[i] as GridHyperLinkColumn).DataTextField;

        if (dataField == "")
          continue;

        string nameFlag = "";
        if (check == chkLvreo)
          nameFlag = "Flag1";
        else if (check == chkFinancial)
          nameFlag = "Flag2";
        else if (check == chkEscrow)
          nameFlag = "Flag3";

        DataRow[] drs = dtColumns.Select(string.Format("(NameColumn='{0}') AND ((Flag1 = 0) OR (Flag2 = 0) OR (Flag3 = 0)) AND ({1} = 1)", dataField, nameFlag));
        if (drs.Length > 0)
        {
          gridLvreo.Columns[i].Display = false;

          if (chkLvreo.Checked && Convert.ToBoolean(drs[0]["Flag1"]))
            gridLvreo.Columns[i].Display = true;
          else if (chkFinancial.Checked && Convert.ToBoolean(drs[0]["Flag2"]))
            gridLvreo.Columns[i].Display = true;
          else if (chkEscrow.Checked && Convert.ToBoolean(drs[0]["Flag3"]))
            gridLvreo.Columns[i].Display = true;
        }
      }
    }

    protected void OpenSettings(string nameSettings)
    {
      DataAccess da = new DataAccess();
      DataTable dt = da.GetDataTable("getGridSetting", new string[] { "@NameSettings", "@NameGrid" }, new object[] { nameSettings, gridLvreo.ID });
      if (dt.Rows.Count <= 0)
        return;

      CurrentViewUserId = Convert.ToInt32(dt.Rows[0]["UserId"]);
      CurrentViewFlagGlobal = Convert.ToBoolean(dt.Rows[0]["FlagGlobal"]);
      
      chkLvreo.Checked = Convert.ToBoolean(dt.Rows[0]["Flag1Visible"]);
      chkFinancial.Checked = Convert.ToBoolean(dt.Rows[0]["Flag2Visible"]);
      chkEscrow.Checked = Convert.ToBoolean(dt.Rows[0]["Flag3Visible"]);
      chkRehab.Checked = Convert.ToBoolean(dt.Rows[0]["FlagRehabVisible"]);
      
      new GridSettingsPersister(gridLvreo).LoadSettings(dt.Rows[0]["Settings"].ToString());
      
      if (CurrentViewUserId == Convert.ToInt32(this.CurrentUser.UserId))
      {
        gridLvreo.MasterTableView.EnableHeaderContextMenu = true;
        chkLvreo.Enabled = true;
        chkFinancial.Enabled = true;
        chkEscrow.Enabled = true;
        chkRehab.Enabled = true;
      }
      else
      {
        gridLvreo.MasterTableView.EnableHeaderContextMenu = false;
        chkLvreo.Enabled = false;
        chkFinancial.Enabled = false;
        chkEscrow.Enabled = false;
        chkRehab.Enabled = false;
      }
      gridLvreo.Rebind();

    }

    protected void DeleteSettings(string nameSettings)
    {
      DataAccess da = new DataAccess();
      da.ExecuteProcedure("deleteGridSettings", new string[] { "@NameSettings" }, new object[] { nameSettings });
      GoToEmptyView();
    }

    protected void GoToEmptyView()
    {
      Response.Redirect(Request.Url.AbsoluteUri);
    }

    protected List<string> MainGridColumnsList(RadGrid grid)
    {
      List<string> listColumns = new List<string>();
      
      for (int i = 1; i < grid.Columns.Count; ++i)
      {
        if ((!grid.Columns[i].Display) || (!grid.Columns[i].Visible))
          continue;

        string dataField = "";

        if (grid.Columns[i] is GridBoundColumn)
          dataField = (grid.Columns[i] as GridBoundColumn).DataField;
        else if (grid.Columns[i] is GridTemplateColumn)
          dataField = (grid.Columns[i] as GridTemplateColumn).DataField;
        else if (grid.Columns[i] is GridHyperLinkColumn)
          dataField = (grid.Columns[i] as GridHyperLinkColumn).DataTextField;

        if (dataField == "")
          continue;

        listColumns.Add(dataField);
      }

      return listColumns;
    }

    protected void HideSubGridColumns(List<string> mainColumns, RadGrid grid)
    {
      for (int i = 1; i < grid.Columns.Count; ++i)
      {
        if ((!grid.Columns[i].Display) || (!grid.Columns[i].Visible))
          continue;

        string dataField = "";

        if (grid.Columns[i] is GridBoundColumn)
          dataField = (grid.Columns[i] as GridBoundColumn).DataField;
        else if (grid.Columns[i] is GridTemplateColumn)
          dataField = (grid.Columns[i] as GridTemplateColumn).DataField;
        else if (grid.Columns[i] is GridHyperLinkColumn)
          dataField = (grid.Columns[i] as GridHyperLinkColumn).DataTextField;

        if (dataField == "")
          continue;

        if (mainColumns.IndexOf(dataField) >= 0)
          grid.Columns[i].Display = false;
      }
    }

    protected void LoadView()
    {
      if (ddlNameSettings.SelectedIndex == 0)
        GoToEmptyView();

      OpenSettings(ddlNameSettings.SelectedValue);

      ManageEnabledButtonsView();
      Session["NameSettingsCurrent"] = ddlNameSettings.SelectedValue;
    }

    protected void btnSaveView_Click(Object sender, EventArgs e)
    {
      SaveSettingsAs(ddlNameSettings.SelectedValue, CurrentViewFlagGlobal);
    }

    protected void btnDeleteView_Click(Object sender, EventArgs e)
    {
      DeleteSettings(ddlNameSettings.SelectedValue);
    }

    protected void chkLvreo_OnCheckedChanged(Object sender, EventArgs e)
    {
      SetColumnsByCheck(chkLvreo);
    }

    protected void chkFinancial_OnCheckedChanged(Object sender, EventArgs e)
    {
      SetColumnsByCheck(chkFinancial);
    }

    protected void chkEscrow_OnCheckedChanged(Object sender, EventArgs e)
    {
      SetColumnsByCheck(chkEscrow);
    }

    protected void chkRehab_OnCheckedChanged(Object sender, EventArgs e)
    {
        bool chk = chkRehab.Checked;
        gridLvreo.Columns.FindByDataField("RehabStatus").Display = chk;
        gridLvreo.Columns.FindByDataField("ActualCompDate").Display = chk;
        gridLvreo.Columns.FindByDataField("NotesStatus").Display = chk;
        gridLvreo.Columns.FindByDataField("RehabStartDate").Display = chk;
        gridLvreo.Columns.FindByDataField("ProjectManager").Display = chk;
        gridLvreo.Columns.FindByDataField("EstRehabCompDate").Display = chk;
        gridLvreo.Columns.FindByDataField("CurrentRehabCosts").Display = chk;
        gridLvreo.Columns.FindByDataField("RehabEstimate").Display = chk;
        gridLvreo.Columns.FindByDataField("RehabMiscCosts").Display = chk;
    }

    protected void ddlNameSettings_SelectedIndexChanged(Object sender, EventArgs e)
    {
      LoadView();
    }

    protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
    {
      base.RaisePostBackEvent(sourceControl, eventArgument);

      switch (eventArgument)
      {
        case "RefreshSaveAs":
          SaveSettingsAs(Session["NameSettingsNew"].ToString(), Convert.ToBoolean(Session["FlagGlobalNew"]));
          break;
      }
    }
    #endregion

    void SaveSortedPropertyIdsToSession(string sortExpression)
    {
        DataTable tbl = (dsLvreo.Select(DataSourceSelectArguments.Empty) as DataView).Table;
        List<int> ids = new List<int>();

        if (string.IsNullOrEmpty(sortExpression))
        {
            foreach (DataRow dr in tbl.Rows)
            {
                ids.Add(Convert.ToInt32(dr["PropertyId"]));
            }
        }
        else
        {
            foreach (DataRow dr in tbl.Select("", sortExpression))
            {
                ids.Add(Convert.ToInt32(dr["PropertyId"]));
            }
        }

        Session["AllPropertiesIds"] = ids.ToArray();
    }

    protected void grid_SortCommand(object sender, GridSortCommandEventArgs e)
    {
        SaveSortedPropertyIdsToSession(e.SortExpression + " "
            + (e.NewSortOrder.ToString().StartsWith("Asc") ? "ASC" : "DESC"));
    }    
  }
}